package com.wallet.crypto.trustapp.interact;

import com.wallet.crypto.trustapp.entity.Wallet;
import com.wallet.crypto.trustapp.interact.rx.operator.Operators;
import com.wallet.crypto.trustapp.repository.PasswordStore;
import com.wallet.crypto.trustapp.repository.WalletRepositoryType;

import io.reactivex.Single;

import static com.wallet.crypto.trustapp.interact.rx.operator.Operators.completableErrorProxy;

public class CreateWalletInteract {

    private final WalletRepositoryType walletRepository;
    private final PasswordStore passwordStore;

    public CreateWalletInteract(WalletRepositoryType walletRepository, PasswordStore passwordStore) {
        this.walletRepository = walletRepository;
        this.passwordStore = passwordStore;
    }

    public Single<Wallet> create(String password) {
        return passwordStore.generatePassword()//创建256位随机密码
                .flatMap(masterPassword -> walletRepository
                        .createWallet(password)//创建钱包
                        .compose(Operators.savePassword(passwordStore, walletRepository, password))//保存密码
                        .flatMap(wallet -> passwordVerification(wallet, password)));
    }

    private Single<Wallet> passwordVerification(Wallet wallet, String masterPassword) {
        return passwordStore
                .getPassword(wallet)//获取密码
                .flatMap(password -> walletRepository
                        .exportWallet(wallet, password, password)//输出钱包
                        .flatMap(keyStore -> walletRepository.findWallet(wallet.address)))//寻找钱包
                .onErrorResumeNext(throwable -> walletRepository
                        .deleteWallet(wallet.address, masterPassword)//删除钱包
                        .lift(completableErrorProxy(throwable))//
                        .toSingle(() -> wallet));
    }
}
